new Vue({
  el: '#app',
  data() {
    return {
      rules: {

      },
      form: {
        Delivery_SerialNumber: "",
        Store_SerialNumber: "",
        longitude: '',
        latitude: '',
        Enterprise_Info_SerialNumber: $.cookie('enterprise'),
        Children: {
          delivery_detail: [{
            Delivery_Detail_SerialNumber: '',
            Delivery_SerialNumber: '',
            Delivery_Distance: '',
            Delivery_Amount: '',
            Sales_Amount: ''
          }]
        }
      },
      loading: false,
      isUrl: false,
      tabsname: [],
      map: null, // 存储地图实例
      markerLayer: null, // 存储标记图层
      address: '',
      value1: true,
      value2: true
    }
  },
  mounted() {
    //加载地图
    this.getEnterprise((longitude, latitude) => {
      this.getMap(longitude, latitude)
    });
  },
  methods: {
    tabname() {
      const _this = this;
      $.ajax({
        url: `${DomainName}/getInquiryAction?token=${$.cookie('token')}`,
        type: 'POST',
        data: {
          Data: 'store_info',
        },
        success: function (res) {
          console.log(res);
          _this.tabsname = res;
          // _this.address = res.Store_Address;
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    handleSwitchChange() {
      if (this.value2) {
        this.change3D();
      } else {
        this.change2D();
      }
    },
    getStore_Address() {
      // 获取选中店铺的值
      const selectedStore = this.tabsname.find(item => item.Store_SerialNumber === this.form.Store_SerialNumber);
      // 将店铺地址赋给地址输入框
      if (selectedStore) {
        this.address = selectedStore.Store_Address;
        this.getAddress();
      }
    },
    getAddress() {
      this.loading = true;
      const _this = this;
      $.ajax({
        url: `${DomainName}/getAddressResolutionAction?token=${$.cookie('token')}`,
        type: 'POST',
        data: {
          Address: this.address,
        },
        success: function (res) {
          console.log(res);
          _this.form.longitude = res.Data.lng;
          _this.form.latitude = res.Data.lat;
          let position = new TMap.LatLng(_this.form.latitude, _this.form.longitude);
          // 移动地图中心到指定位置
          _this.map.setCenter(position);
          let marker = null;

          _this.map.on("click", (evt) => {
            // 清除之前的标点
            if (marker) {
              marker.setMap(null);
            }
            // 添加新的标点
            marker = new TMap.MultiMarker({
              map: _this.map,
              geometries: [{
                position: evt.latLng,
              }]
            });
    
            _this.form.longitude = evt.latLng.getLng().toFixed(6);
            _this.form.latitude = evt.latLng.getLat().toFixed(6);
            _this.getLocation();
            // 移动地图中心到新标点位置
            _this.map.setCenter(evt.latLng);
          });
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    getLocation() {
      this.loading = true;
      const _this = this;
      $.ajax({
        url: `${DomainName}/getLocationResolutionAction?token=${$.cookie('token')}`,
        type: 'POST',
        data: {
          latitude: this.form.latitude,
          longitude: this.form.longitude,
        },
        success: function (res) {
          console.log(res);
          _this.address = res.Data.address + res.Data.formatted_addresses.recommend;
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    getEnterprise(callback) {
      this.loading = true;
      const _this = this;
      $.ajax({
        url: `${DomainName}/getEnterpriseLocationAction?token=${$.cookie('token')}`,
        type: 'GET',
        success: function (res) {
          console.log(res);
          // _this.form.longitude = res.Data.longitude;
          // _this.form.latitude = res.Data.latitude;
          callback(res.Data.longitude, res.Data.latitude);
        },
        error: function () {
          _this.$message.error("操作失败，请稍后再试")
        },
        complete: function (XMLHttpRequest) {
          _this.loading = false
          if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
            window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
          }
        }
      })
    },
    getMap(longitude, latitude) {
      this.map = new TMap.Map("container", {
        center: new TMap.LatLng(latitude, longitude),
        zoom: 17,
        pitch: 45, //设置俯仰角度（0~45）,
        viewMode: '3D',
      });
      this.markerLayer = new TMap.MultiMarker({
        map: this.map
      });
      let marker = null;

      this.map.on("click", (evt) => {
        // 清除之前的标点
        if (marker) {
          marker.setMap(null);
        }
        // 添加新的标点
        marker = new TMap.MultiMarker({
          map: this.map,
          geometries: [{
            position: evt.latLng,
          }]
        });

        this.form.longitude = evt.latLng.getLng().toFixed(6);
        this.form.latitude = evt.latLng.getLat().toFixed(6);
        this.getLocation();
        // 移动地图中心到新标点位置
        this.map.setCenter(evt.latLng);
      });
    },
    change2D() {
      this.map.setViewMode('2D');
    },
    change3D() {
      this.map.setViewMode('3D');
      this.map.setPitch(70);
    },
    submitForm() {
      const _this = this;
      this.$refs['contract'].validate((valid) => {
        _this.loading = true
        if (valid) {
          $.ajax({
            url: `${DomainName}/getAddAction?token=${$.cookie('token')}`,
            type: 'POST',
            data: {
              Data: JSON.stringify({
                delivery_info: [_this.form]
              }),
            },
            success: function (res) {
              if (res.Status === 'success') {
                _this.$message.success("提交成功")
                window.history.go(-1);
              } else {
                _this.$message.error("提交失败，请稍后再试")
              }
            },
            error: function () {
              _this.$message.error("操作失败，请稍后再试")
            },
            complete: function (XMLHttpRequest) {
              _this.loading = false
              if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                window.parent.document.location.href = "../../../" + XMLHttpRequest.getResponseHeader("CONTENTPATH");
              }
            }
          })
        }
      })

    },
    add_system_model_mark() {
      this.form.Children.delivery_detail.push({
        Delivery_Detail_SerialNumber: '',
        Delivery_SerialNumber: '',
        Delivery_Distance: '',
        Delivery_Amount: '',
        Sales_Amount: ''
      })
      console.log(this.form);
    },
    remove_system_model_mark() {
      if (this.form.Children.delivery_detail.length > 1) {
        this.form.Children.delivery_detail.pop()
      } else {
        this.$message({
          message: '不能在删除了',
          type: 'warning'
        })
      }
    },
  },
  created() {
    this.tabname();
  }
})